#!/bin/bash

TS_TOPDIR="${0%/*}/../.."
TS_DESC="fstab-fallback"

. "$TS_TOPDIR"/functions.sh
ts_init "$*"

ts_check_test_command "$TS_CMD_MOUNT"
ts_check_test_command "$TS_CMD_UMOUNT"
ts_check_test_command "$TS_CMD_FINDMNT"
ts_check_test_command "$TS_CMD_LOSETUP"
ts_check_enosys_syscalls open_tree fsopen mount_setattr

ts_skip_nonroot

test_mount_fallback() {
	ts_init_subtest "$1"

	MY_SOURCE="${TS_MOUNTPOINT}-src"

	mkdir -p "$MY_SOURCE"
	mkdir -p "$TS_MOUNTPOINT"

	"$TS_CMD_ENOSYS" $2 -- "$TS_CMD_MOUNT" --bind "$MY_SOURCE" "$TS_MOUNTPOINT" \
		>> "$TS_OUTPUT" 2>> "$TS_ERRLOG"
	[ "$?" = "0" ] || ts_log "error: mount $TS_MOUNTPOINT"

	"$TS_CMD_FINDMNT" --mountpoint "$TS_MOUNTPOINT" &> /dev/null
	[ $? -eq 0 ] || ts_die "Not found target (mount failed?)"

	"$TS_CMD_UMOUNT" "$TS_MOUNTPOINT" || ts_die "Cannot umount $TS_MOUNTPOINT"

	ts_finalize_subtest
}

test_mount_fallback "open_tree" "-s open_tree"
test_mount_fallback "fsopen" "-s fsopen"


ts_device_init
DEVICE=$TS_LODEV
mkfs.ext2 $DEVICE &> /dev/null || ts_die "Cannot make ext2 on $DEVICE"
ts_udevadm_settle "$DEVICE"

# use the same in all next subtests
MOUNTPOINT=$TS_MOUNTPOINT
mkdir -p "$MOUNTPOINT"


ts_init_subtest "later-fsopen"
$TS_CMD_ENOSYS -s fsopen -- "$TS_CMD_MOUNT" -t foo,bar,ext2 "$DEVICE" "$MOUNTPOINT" \
		>> $TS_OUTPUT 2>> $TS_ERRLOG
ts_is_mounted $DEVICE || ts_log "Cannot find $DEVICE in /proc/mounts"
mkdir -p ${MOUNTPOINT}/subdir
$TS_CMD_UMOUNT $MOUNTPOINT >> $TS_OUTPUT 2>> $TS_ERRLOG
ts_finalize_subtest


ts_init_subtest "subdir"
$TS_CMD_ENOSYS -s fsopen -s open_tree -- \
	"$TS_CMD_MOUNT" -o X-mount.subdir=subdir "$DEVICE" "$MOUNTPOINT" \
	>> $TS_OUTPUT 2>> $TS_ERRLOG
ts_is_mounted $DEVICE || ts_log "Cannot find $DEVICE in /proc/mounts"
$TS_CMD_UMOUNT $MOUNTPOINT
ts_finalize_subtest


ts_init_subtest "mount_setattr"
"$TS_CMD_MOUNT" "$DEVICE" "$MOUNTPOINT"  >> $TS_OUTPUT 2>> $TS_ERRLOG
ts_is_mounted $DEVICE || ts_log "Cannot find $DEVICE in /proc/mounts"
$TS_CMD_ENOSYS -s mount_setattr -- \
	"$TS_CMD_MOUNT" -o remount,ro "$MOUNTPOINT" \
	>> $TS_OUTPUT 2>> $TS_ERRLOG
$TS_CMD_FINDMNT --kernel --mountpoint "$MOUNTPOINT" --options "ro" &> /dev/null
[ "$?" == "0" ] || ts_die "Cannot find read-only in $MOUNTPOINT in /proc/self/mountinfo"
$TS_CMD_ENOSYS -s mount_setattr -- \
 	"$TS_CMD_MOUNT" --make-slave "$MOUNTPOINT" \
 	>> $TS_OUTPUT 2>> $TS_ERRLOG
$TS_CMD_FINDMNT -n --kernel --mountpoint "$MOUNTPOINT" -o PROPAGATION >> $TS_OUTPUT
$TS_CMD_UMOUNT $MOUNTPOINT
ts_finalize_subtest


ts_finalize

